package com.aiton.bamin.bamindaijiadrier.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.widget.AvatarImageCardIdFanView;
import com.aiton.administrator.shane_library.shane.widget.AvatarImageCardIdZhengView;
import com.aiton.administrator.shane_library.shane.widget.AvatarImageDrivingFanView;
import com.aiton.administrator.shane_library.shane.widget.AvatarImageDrivingZhengView;
import com.aiton.administrator.shane_library.shane.widget.AvatarImageView;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;

import cn.qqtheme.framework.picker.DatePicker;
import cz.msebera.android.httpclient.Header;

public class ApplyPictureActivity extends ZjbBaseActivity implements View.OnClickListener {

    //    private AvatarImageView mImg_avatar;
    private AvatarImageCardIdZhengView mImg_cardId_front;
    private AvatarImageCardIdFanView mImg_cardId_reverse;
    private boolean isAvatar;
    private boolean isCardIdFront;
    private boolean isCardIdReverse;
    private AvatarImageDrivingZhengView mImg_driving_front;
    private AvatarImageDrivingFanView mImg_driving_reverse;
    private String mName;
    private String mPhone;
    private String mCardId;
    private String mDrivingId;
    private String mDrivingTime;
    private String mEmergency;
    private String mAvatarPath;
    private String mCardIdZhengPath;
    private String mCardIdFanPath;
    private String mDrivingFrontPath;
    private String mDrivingFanPath;
    private int mSex;
    private String mDriving_city;
    private AsyncHttpClient mAsyncHttpClient;
    private EditText mEdt_drivingId;
    private EditText mEdt_drivingTime;
    private User mUser;
    private boolean checkCardIdZhend;
    private boolean checkCardIdFan;
    private boolean checkDriverZheng;
    private boolean checkDriverFan;
    private boolean checkAvatar;
    private AvatarImageView mImg_avatar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_picture);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //申请CAMERA权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    Constant.PERMISSION.CAMERA);//自定义的code
        }


        init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        mImg_avatar.setFileName("touxian_upload");
        mImg_cardId_front.setFileName("cardId_front_upload");
        mImg_cardId_reverse.setFileName("cardId_reverse_upload");
        mImg_driving_front.setFileName("driving_front_upload");
        mImg_driving_reverse.setFileName("driving_reverse_upload");
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.btn_sure).setOnClickListener(this);
        mEdt_drivingTime.setOnClickListener(this);


        //头像控件监听
        mImg_avatar.setAfterCropListener(new AvatarImageView.AfterCropListener() {
            @Override
            public void afterCrop(Bitmap photo) {

                Toast.makeText(ApplyPictureActivity.this, "选择头像成功", Toast.LENGTH_SHORT).show();
                postAvatarFile(mImg_avatar.getFileName());
                Log.e("ApplyPictureActivity", "选择头像: --->>" + mImg_avatar.getFileName().getPath());

            }
        });
        //身份证正面控件监听
        mImg_cardId_front.setAfterCropListener(new AvatarImageCardIdZhengView.AfterCropListener() {
            @Override
            public void afterCrop(Bitmap photo) {
                Toast.makeText(ApplyPictureActivity.this, "选择身份证正面成功", Toast.LENGTH_SHORT).show();

                postCardIdZhengFile(mImg_cardId_front.getFileName());
                Log.e("ApplyPictureActivity", "选择身份证正面: --->>" + mImg_cardId_front.getFileName().getPath());


            }
        });
        //身份证反面控件监听
        mImg_cardId_reverse.setAfterCropListener(new AvatarImageCardIdFanView.AfterCropListener() {
            @Override
            public void afterCrop(Bitmap photo) {
                Toast.makeText(ApplyPictureActivity.this, "选择身份证反面成功", Toast.LENGTH_SHORT).show();
                postCardIdFnaFile(mImg_cardId_reverse.getFileName());
                Log.e("ApplyPictureActivity", "选择身份证反面: --->>" + mImg_cardId_reverse.getFileName().getPath());

            }
        });
        //驾驶证正面控件监听
        mImg_driving_front.setAfterCropListener(new AvatarImageDrivingZhengView.AfterCropListener() {
            @Override
            public void afterCrop(Bitmap photo) {
                Toast.makeText(ApplyPictureActivity.this, "选择驾驶证正面成功", Toast.LENGTH_SHORT).show();
                postDriverZhengFile(mImg_driving_front.getFileName());
                Log.e("ApplyPictureActivity", "选择驾驶证正面: --->>" + mImg_driving_front.getFileName().getPath());

            }
        });
        //驾驶证反面控件监听
        mImg_driving_reverse.setAfterCropListener(new AvatarImageDrivingFanView.AfterCropListener() {
            @Override
            public void afterCrop(Bitmap photo) {
                Toast.makeText(ApplyPictureActivity.this, "选择驾驶证反面成功", Toast.LENGTH_SHORT).show();
                postDriverFanFile(mImg_driving_reverse.getFileName());
                Log.e("ApplyPictureActivity", "选择驾驶证反面: --->>" + mImg_driving_reverse.getFileName().getPath());
            }
        });


    }

    @Override
    protected void initSP() {
    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mUser = (User) intent.getSerializableExtra(Constant.INTENT_KEY.USER);

    }

    @Override
    protected void findID() {

        mImg_avatar = (AvatarImageView) findViewById(R.id.img_avatar);
        mImg_cardId_front = (AvatarImageCardIdZhengView) findViewById(R.id.img_cardId_front);
        mImg_cardId_reverse = (AvatarImageCardIdFanView) findViewById(R.id.img_cardId_reverse);
        mImg_driving_front = (AvatarImageDrivingZhengView) findViewById(R.id.img_driving_front);
        mImg_driving_reverse = (AvatarImageDrivingFanView) findViewById(R.id.img_driving_reverse);
        mEdt_drivingId = (EditText) findViewById(R.id.edt_drivingId);
        mEdt_drivingTime = (EditText) findViewById(R.id.edt_drivingTime);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //在拍照、选取照片、裁剪Activity结束后，调用的方法
//        if (mImg_avatar != null) {
//            mImg_avatar.onActivityResult(requestCode, resultCode, data);
//        }
        if (mImg_cardId_front != null) {
            mImg_cardId_front.onActivityResult(requestCode, resultCode, data);
        }
        if (mImg_cardId_reverse != null) {
            mImg_cardId_reverse.onActivityResult(requestCode, resultCode, data);

        }
        if (mImg_driving_front != null) {
            mImg_driving_front.onActivityResult(requestCode, resultCode, data);

        }
        if (mImg_driving_reverse != null) {
            mImg_driving_reverse.onActivityResult(requestCode, resultCode, data);

        }
        if (mImg_avatar != null) {
            mImg_avatar.onActivityResult(requestCode, resultCode, data);

        }


    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.btn_sure:
                postInfo();

                break;
            case R.id.edt_drivingTime://选择时间
                chooseTimne();
                break;
        }
    }

    /**
     * 驾照时间选择器
     */
    public void chooseTimne() {
        DatePicker picker = new DatePicker(this, DatePicker.YEAR_MONTH);
//        picker.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        picker.setRangeStart(1980, 1, 1);
        picker.setRangeEnd(2011, 12, 30);
        picker.setSelectedItem(2011, 12, 1);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {
            @Override
            public void onDatePicked(String year, String month) {
                mEdt_drivingTime.setText(year + " - " + month);
            }
        });
        picker.show();
    }


    private void showSingleDialog(String title, String confirm) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, title, confirm);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }

    private void showSuccessSingleDialog(String title, String confirm) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, title, confirm);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                finishTo();
            }
        });
        singleBtnDialog.show();
    }

    @Override
    public void onBackPressed() {

    }

    /**
     * 上传图片
     *
     * @param uploadFile
     */
    public void postAvatarFile(Uri uploadFile) {
        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);

        String actionUrl = Constant.Url.CUSTOMERIMAGE;
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("driver_id", mUser.getDatas().getId());
            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    try {
                        checkAvatar=true;
                    } catch (Exception e) {
                        checkAvatar=false;
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "失败");
                    checkAvatar=false;
                }
            });
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        ImageLoader.getInstance().clearDiskCache();
    }

    /**
     * 上传身份证正面
     *
     * @param uploadFile
     */
    public void postCardIdZhengFile(Uri uploadFile) {

        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);

        String actionUrl = Constant.Url.CARDIDZHENG;
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("driver_id", mUser.getDatas().getId());
            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    try {
                        String s = new String(responseBody);

                        checkCardIdZhend = true;
                    } catch (Exception e) {
                        checkCardIdZhend = false;
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "身份证正面失败");
                    checkCardIdZhend = false;
                }
            });
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        ImageLoader.getInstance().clearDiskCache();
    }

    /**
     * 上传身份证反面
     *
     * @param uploadFile
     */
    public void postCardIdFnaFile(Uri uploadFile) {

        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);

        String actionUrl = Constant.Url.CARDIDFAN;
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("driver_id", mUser.getDatas().getId());
            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    try {
                        String imgUrl = new String(responseBody);
                        checkCardIdFan = true;
                    } catch (Exception e) {
                        checkCardIdFan = false;

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "身份证反面失败");
                    checkCardIdFan = false;
                }
            });
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        ImageLoader.getInstance().clearDiskCache();
    }

    /**
     * 上传驾驶证正面
     *
     * @param uploadFile
     */
    public void postDriverZhengFile(Uri uploadFile) {

        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);

        String actionUrl = Constant.Url.DRIVERZHENG;
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("driver_id", mUser.getDatas().getId());
            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    try {
                        String imgUrl = new String(responseBody);
                        checkDriverZheng = true;
                    } catch (Exception e) {
                        checkDriverZheng = false;

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "驾驶证正面失败");
                    checkDriverZheng = false;
                }
            });
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        ImageLoader.getInstance().clearDiskCache();
    }

    /**
     * 上传驾驶证反面
     *
     * @param uploadFile
     */
    public void postDriverFanFile(Uri uploadFile) {

        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);
        String actionUrl = Constant.Url.DRIVERFAN;
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("driver_id", mUser.getDatas().getId());
            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    try {
                        String imgUrl = new String(responseBody);
                        checkDriverFan = true;
                    } catch (Exception e) {
                        checkDriverFan = false;

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "驾驶证反面失败");
                    checkDriverFan = false;
                }
            });
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        ImageLoader.getInstance().clearDiskCache();
    }

    /**
     * 上传司机驾驶证信息
     */
    private void postInfo() {
        if (checkDriverFan && checkDriverZheng && checkCardIdFan && checkCardIdZhend) {
            String url = Constant.Url.DRIVERINFO;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("id", mUser.getDatas().getId());
            params.put("drivingId", mEdt_drivingId.getText().toString().trim());
            params.put("getIdTime", mEdt_drivingTime.getText().toString().trim());
            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    Log.e("ApplyPictureActivity", "司机驾驶证信息: --->>" +s );

                    try {
                        showSuccessSingleDialog("上传成功","确定");
                    } catch (Exception e) {

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });
        } else {
            Toast.makeText(ApplyPictureActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
        }
    }


}
